package com.huangliusong.desigin.pattern.structual.proxy.dynamicproxy;

import com.huangliusong.desigin.pattern.structual.proxy.Order;
import com.huangliusong.desigin.pattern.structual.proxy.db.DataSourceContextHolder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author huangliusong
 * @since 2018/10/13
 * {@link InvocationHandler}
 */
public class OrderServiceDynamicProxy implements InvocationHandler {
    private Object target;

    public OrderServiceDynamicProxy(Object target) {
        this.target = target;
    }

    public Object bind() {
        Class clas = target.getClass();
        return Proxy.newProxyInstance(clas.getClassLoader(), clas.getInterfaces(), this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object argObject=args[0];
        beforeMethod(argObject);
        Object object=method.invoke(target,args);
        afterMethod();
        return object;
    }

    private void beforeMethod(Object obj) {
        int userId = 0;
        System.out.println("动态代理：before core");
        if (obj instanceof Order) {
            Order order = (Order) obj;
            userId = order.getUserId();
            int dbRouter = userId % 2;
            System.out.println("静态代理分配到[DB" + dbRouter + "]处理数据");
            DataSourceContextHolder.setDBType(String.valueOf(dbRouter));
            System.out.println("静态代理before code");
        }
    }

    private void afterMethod() {
        System.out.println("动态代理");

    }
}
